//
//  MessageRequest.m
//  iHeima
//
//  Created by he chao on 6/9/14.
//  Copyright (c) 2014 leon. All rights reserved.
//

#import "MessageRequest.h"
#import "ChatBoard.h"
#import "ChatDB.h"

@implementation MessageRequest
DEF_SINGLETON(MessageRequest)

#define kMessageTime 5

- (void)load{
    [super load];
    isRequest = NO;
    [self startRequest];
}

- (void)unload
{
    [timer invalidate];
}

- (void)startRequest{
    timer = [NSTimer scheduledTimerWithTimeInterval:kMessageTime target:self selector:@selector(checkMessage) userInfo:nil repeats:YES];
    [timer fire];
}

- (void)cancelRequest{
    [timer invalidate];
}

- (void)checkMessage{
    if (!isRequest) {
        [self getAllMessage];
    }
}

- (void)getAllMessage{
    isRequest = YES;
    NSString *strUid = kUserInfo[@"uid"];
    BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apichat/listmessage",kBaseUrl]].PARAM(@"uid",strUid);
    /*
    BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apichat/listmessage",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"rid",self.strRid);
    if (self.isMeeting) {
        request.PARAM(@"type",@"1");
        request.tag = 9527;
    }
    else {
        request.PARAM(@"type",@"0");
        request.tag = 9528;
    }*/
}

- (void)handleRequest:(BeeRequest *)request
{
    if(request.failed)
    {
        [[BeeUITipsCenter sharedInstance] dismissTips];
        NETWORK_ERROR
    }
    else if (request.succeed)
    {
        isRequest = NO;
        id json = [request.responseString mutableObjectFromJSONString];
        NSLog(@"%@",json);
        switch ([json[@"status"] intValue]) {
            case 1:
            {
                if ([json[@"res"] count]>0) {
                    NSLog(@"zzz");
                    [self saveChat:json[@"res"]];
                    if (self.chatBoard) {
                        [self.chatBoard receiveMsg:json[@"res"]];
                    }
                    else {
                        NSMutableArray *arrayUnread = [[[NSUserDefaults standardUserDefaults] valueForKey:@"unread"] mutableCopy];
                        if (!arrayUnread) {
                            arrayUnread = [[NSMutableArray alloc] init];
                        }
                        for (int i = 0; i < [json[@"res"] count]; i++) {
                            NSMutableDictionary *dict = json[@"res"][i];
                            if ([dict[@"type"] intValue]==0) {
                                BOOL isFind = NO;
                                for (int j = 0; j < arrayUnread.count; j++) {
                                    NSMutableDictionary *dict2 = [arrayUnread[j] mutableCopy];
                                    if ([dict2[@"uid"] intValue]==[dict[@"rid"] intValue] && [dict2[@"rid"] intValue]==[dict[@"uid"] intValue]) {
                                        isFind = YES;
                                        int count = [dict2[@"count"] intValue]+1;
                                        [dict2 setValue:[NSString stringWithFormat:@"%d",count] forKey:@"count"];
                                        [arrayUnread replaceObjectAtIndex:j withObject:dict2];
                                        break;
                                    }
                                }
                                if (!isFind) {
                                    NSMutableDictionary *dictNew = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"1",@"count",dict[@"rid"],@"uid",dict[@"uid"],@"rid", nil];//[NSMutableDictionary dictionaryWithObjectsAndKeys:@"1",@"count",dict[@"rid"],@"rid",dict[@"uid"],@"uid", nil];
                                    [arrayUnread addObject:dictNew];
                                }
                            }
                        }
                        
                        [[NSUserDefaults standardUserDefaults] setObject:arrayUnread forKey:@"unread"];
                        [self postNotification:@"newMessage"];
                    }
                }
                
            }
                break;
                
            default:
                break;
        }
    }
}

- (void)saveChat:(id)json{
    for (int i = 0; i < [json count]; i++) {
        //[[ChatDB sharedInstance] load];
        NSMutableDictionary *dict = json[i];
        if ([dict[@"images"] count]>0 && [dict[@"content_type"] intValue]==2) {
            [dict setObject:dict[@"images"][0][@"path"] forKey:@"content"];
        }
        [[ChatDB sharedInstance] insert:dict];
    }
}

@end
